package com.wanghua.mall.ware.service.impl;

import com.wanghua.mall.ware.entity.PurchaseDetailEntity;
import com.wanghua.mall.ware.service.PurchaseDetailService;
import com.wanghua.mall.ware.service.WareSkuService;
import com.wanghua.mall.ware.vo.FinishPurchaseVo;
import com.wanghua.mall.ware.vo.MergePurchaseDetailVo;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanghua.common.utils.PageUtils;
import com.wanghua.common.utils.Query;

import com.wanghua.mall.ware.dao.PurchaseDao;
import com.wanghua.mall.ware.entity.PurchaseEntity;
import com.wanghua.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Resource
    private PurchaseDetailService purchaseDetailService;
    @Resource
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        String status = (String) params.get("status");
        if (StringUtils.hasLength(status)) {
            queryWrapper.like("status", status);
        }
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            queryWrapper.like("assignee_name", key);
        }
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 查询未领取的采购单
     */
    @Override
    public PageUtils listUnReceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        //0-新建,1-已分配,2-已领取,3-已完成,4-有异常
        queryWrapper.in("status", 0, 1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    //合并采购需求
    @Transactional
    @Override
    public void mergePurchaseDetail(MergePurchaseDetailVo mergePurchaseDetailVo) {
        System.out.println(mergePurchaseDetailVo);
        Long purchaseId = mergePurchaseDetailVo.getPurchaseId();
        List<Long> purchaseDetailIds = mergePurchaseDetailVo.getItems();

        PurchaseEntity purchaseEntity;
        if (purchaseId == null) {
            purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(0);
            baseMapper.insert(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        Long finalPurchaseId = purchaseId;
        purchaseDetailService.updateBatchById(purchaseDetailIds.stream().map((purchaseDetailId) -> {
            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(purchaseDetailId);
            //新建/已分配/正在采购/已完成/采购失败
            purchaseDetailEntity.setStatus(1);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            return purchaseDetailEntity;
        }).collect(Collectors.toList()));


    }

    //领取采购单
    @Override
    public void receivePurchase(List<Long> purchaseIds) {
        //确认采购单是新建和已分配状态
        //改变采购单状态
        this.updateBatchById(purchaseIds.stream()
                .map(purchaseId -> baseMapper.selectById(purchaseId))
                .filter(purchaseEntity -> purchaseEntity.getStatus() <= 1)
                .map(item -> {
                    item.setStatus(2);
                    return item;
                })
                .collect(Collectors.toList()));
        //改变采购单对应的采购需求的状态
        purchaseIds.forEach((purchaseId) -> {
            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", purchaseId));
            purchaseDetailService.updateBatchById(purchaseDetailEntityList.stream().map((purchaseDetailEntity) -> {
                purchaseDetailEntity.setStatus(2);
                return purchaseDetailEntity;
            }).collect(Collectors.toList()));
        });

    }

    //完成采购
    @Transactional
    @Override
    public void donePurchase(FinishPurchaseVo finishPurchaseVo) {
        //1.改变采购单对应的采购需求的状态
        List<FinishPurchaseVo.Item> items = finishPurchaseVo.getItems();
        AtomicBoolean flag = new AtomicBoolean(true);//标志所有采购项是否全部成功
        purchaseDetailService.updateBatchById(items.stream().map((item) -> {
            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(item.getItemId());
            purchaseDetailEntity.setStatus(item.getStatus());
            if (flag.get() && item.getStatus() == 4) flag.set(false);
            //3.将成功采购的物品进行入库
            wareSkuService.addStock(purchaseDetailEntity.getSkuId(), purchaseDetailEntity.getWareId(), purchaseDetailEntity.getSkuNum());
            return purchaseDetailEntity;
        }).collect(Collectors.toList()));
        //2.改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(finishPurchaseVo.getPurchaseId());
        if (flag.get()) {
            purchaseEntity.setStatus(3);//成功
        } else {
            purchaseEntity.setStatus(4);//失败
        }
        baseMapper.updateById(purchaseEntity);
    }

}